// pages/kind/kind.js
var config = require('../../config');
var util = require('../../utils/util.js');
var app = getApp();
// 开发时用本地数据测试-调用接口按kind查询数据
var kind_data = [];
Page({
  data: {
    host: config.service.host + '/',
    // 窗口高度
    winHeight: 0,
    // 预设当前项的值
    currentTab: 0,
    // tab标题的滚动条位置
    scrollLeft: 0,
    // 种类及数据
    kindData: [],
    topBottom: ''
  },
  // 滚动切换标签样式
  switchTab: function (e) {
    this.setData({
      currentTab: e.detail.current
    });
    this.checkCor();
  },
  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    var cur = e.target.dataset.current;
    if (this.data.currentTaB != cur) {
      this.setData({
        currentTab: cur
      })
    }
  },
  // 判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    if (this.data.currentTab > 3) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  onLoad: function () {
    var self = this;
    wx.request({
      url: config.service.kind_data,
      data: { istest: app.globalData.testUser },
      method: "POST",
      success(result) {
        self.groupByKind(result.data);
        console.log(kind_data);
        // // 数据加载后执行
        var swp = false;
        kind_data.forEach(function (item) {
          var l = item.list.length;
          var times = 3 - l % 3;
          times = times === 3 ? 0 : times;
          for (var i = 0; i < times; i++) {
            item.list.push({
              id: null
            });
          }
          if (!swp) swp = (item.list.length > 6);
        });
        self.setData({
          kindData: kind_data,
          topBottom: swp ? 'position: static; margin-top: 41px;' : 'position: fixed; top: 41px;'
        })
      },
      fail(error) {
        util.showModel('请求失败，请重试！', error);
      }
    });
    // 高度自适应
    this.setData({
      winHeight: app.globalData.clientHeight - 41
    });
  },
  groupByKind: function (list) {
    kind_data.push({
      kind: 0,
      kind_name: '全部',
      list: list
    });
    var map = {},
      dest = [];
    for (var i = 0; i < list.length; i++) {
      var ai = list[i];
      if (!map[ai.kind]) {
        dest.push({
          kind: ai.kind,
          kind_name: ai.kind_name,
          list: [ai]
        });
        map[ai.kind] = ai;
      } else {
        for (var j = 0; j < dest.length; j++) {
          var dj = dest[j];
          if (dj.kind == ai.kind) {
            dj.list.push(ai);
            break;
          }
        }
      }
    }
    kind_data = kind_data.concat(dest);
  },
  cardClik: function (e) {
    var card = this.data.kindData[this.data.currentTab].list[e.currentTarget.dataset.index];
    app.globalData.cardInfo = card;
    wx.navigateTo({
      url: `../${card.style}/card`
    });
  }
})
